package com.github.dote.mio.client;

import com.github.dote.mio.protocal.CharsetHelper;
import com.github.dote.mio.protocal.Packet;
import com.github.dote.mio.protocal.PacketType;
import com.github.dote.mio.util.JsonUtil;

public class PacketHandler {

    private IOClient client;


    public PacketHandler(IOClient client) {
        this.client = client;
    }


    public void messageReceived(byte[] buff, int len) {
        String packetJsonString = CharsetHelper.getString(buff, len);
        Packet packet = JsonUtil.parseObject(packetJsonString, Packet.class);

        switch (packet.getType()) {
            case PacketType.KEEP_ALIVE: {
                client.getKeepAliveDaemon().updateGetKeepAliveResponseFromServerTimstamp();
                break;
            }
            case PacketType.ACK: {
                client.getAckSendTask().remove(packet.getAckId());
                break;
            }
            case PacketType.EVENT_MESSAGE: {
                checkAndSendAckPakcet(client, packet);
                if (!client.getAckReceiveTask().hasRecieved(packet.getAckId())) {
                    client.getEventManager().onEvent(client, packet.getSubType(), packet.getDataContent());
                }

                break;
            }
            default:
                break;
        }
    }

    private void checkAndSendAckPakcet(IOClient client, Packet packet) {
        if (packet.isAck() && packet.getAckId() != null && !"".equals(packet.getAckId())) {
            Packet ackPacket = packet.clone();
            ackPacket.setType(PacketType.ACK);
            client.send(ackPacket);
        }
    }

}
